package com.example.stmall.manager.controller.api;

import com.example.stmall.manager.entity.Category;
import com.example.stmall.manager.entity.Result;
import com.example.stmall.manager.service.CategoryService;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController     //相当于Controller注解与ResponseBody的结合体
                    //1.将当前类放到Spring的Bean容器中
                    //2.所有处理器方法，返回JSON格式数据
@RequestMapping("/api/category")
public class APICategoryController {
    @Resource
    private CategoryService categoryService;
    /**
     * 添加，使用POST请求
     */
    @PostMapping
    public Result add(@RequestBody Category category){
        //@RequestBody注释作用是解析客户端发送来的JSON
        try {
            int code = categoryService.add(category);
            //添加成功
            return  Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            //添加失败
            return Result.error(e.getMessage());
        }
    }
    /**
     * 删除，delete
     */
    @DeleteMapping
    public Result remove(Integer id){
        try {
            int code = categoryService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    /**
     * 修改，put
     */
    @PutMapping
    public Result edit(@RequestBody Category category){
        try {
            int code = categoryService.edit(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    /**
     * 根据条件查询 get
     */
    @GetMapping
    public Result get(Integer page,Integer limit,Category category){
        if(page == null) {   //如果没有分页信息
            List<Category> list = categoryService.search(category);
            return Result.success(list);
        }else{
            PageInfo pageInfo = categoryService.searchByPage(page,limit,category);
            return Result.success(pageInfo);
        }
    }
    /**
     * 根据ID进行查询，get
     * 通过路径参数来传递ID,放在URL上的参数
     */
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        //PathVariable去除路径中的参数，绑定到id上
        Category category = categoryService.getById(id);

        if(category == null){
            return Result.error("ID不存在！！！");
        }else{
            return Result.success(category);
        }
    }
    /**
     *
     */
}
